const SocketIo = require('socket.io');

var io; // socket实例
var allSocket = new Map(); // 房间
var rooms = new Map(); // 房间

/**
 * @description 初始化
 * @param {server} http服务器
 * */
const initSocketIo = (server) => {
    io = SocketIo.listen(server)
    io.set('origins', '*:*')

    //监听客户端链接,回调函数会传递本次链接的socket
    // namespace命名空间 /webrtc
    const webrtc = io.of('/webrtc').on('connection', socket => {
        console.log(`connect: %c${socket.id}`, 'color:green;');
        allSocket.set(socket.id, socket);
        rooms.set(socket.id, socket.rooms);

        // 监听客户端发送的信息
        socket.on("sentToServer", message => {
            // 给客户端返回信息
            socket.emit("sendToClient", `connect success:${socket.id}`);
        });
        socket.on("broadcastRoom", message => {
            // webrtc.in(socket.id).emit("message", message);
            Object.keys(socket.rooms).forEach(roomid => {
                webrtc.to(roomid).emit("message", `${roomid}:${message}`); // to 不包括自己
            });
        });
        socket.on("send", message => {
            // socket.emit("message", message);
            socket.emit("message", message);
        });
        socket.on("allSocket", message => {
            socket.emit('resSocket', Object.keys(webrtc.sockets));
        })
        socket.on("allRoom", message => {
            socket.emit('resRoom', getAllRoom());
        })
        socket.on("createRoom", message => {
            createRoom(socket, Date.now());
            socket.emit('resRoom', getAllRoom());
        })
        socket.on("joinRoom", message => {
            joinRoom(socket, message);
        })
        socket.on("removeRoom", message => {
            removeRoom(socket, message);
            socket.emit('resRoom', getAllRoom());
        })
        // webrtc
        socket.on("establishConnect", (message) => {
            console.log(message)
            webrtc.in(message.target).emit("setSDP", message);
        })
        socket.on("candidate", (message) => {
            console.log(message)
            webrtc.in(message.target).emit("setCandidate", message);
        })
        // 监听连接断开事件
        socket.on("disconnect", (e) => {
            allSocket.delete(socket.id);
            rooms.delete(socket.id);
            console.log(`disconnect: %c${socket.id}`, 'color:red;');
        });
    });

    console.log(`socketio服务启动成功：/webrtc`);
}

function createRoom(socket, roomid) {
    rooms.set(roomid, {});
    console.log(`【${socket.id}】createroom【${roomid}】`);
}
function removeRoom(socket, roomid) {
    rooms.delete(roomid)
    console.log(`removeRoom【${roomid}】`);
}
function getAllRoom() {
    let roomKeys = [];
    rooms.forEach((v, k, m) => {
        roomKeys.push(k);
    });
    return roomKeys;
}

function joinRoom(socket, roomid) {
    socket.join(roomid);
    console.log(`rooms:【${socket.id}】join【${roomid}】`);
}


module.exports = {
    initSocketIo,
    createRoom,
    joinRoom,
}
